const mongoose = require('mongoose');
const dbConfig = require('../config/db');

let openDB = dbname => {
    // mongoose.connect('mongodb://localhost:27017/demo');
    // let db = mongoose.connection;

    let db = mongoose.createConnection(`mongodb://${dbConfig.user}:${dbConfig.password}@${dbConfig.host}:${dbConfig.port}/${dbname}?authSource=${dbConfig.db}`)

    db.on('connected', () => {
        console.log(`Mongoose connected on: mongodb://${dbConfig.host}:${dbConfig.port}/${dbname}`);
    });

    db.on('error', err => {
        mongoose.connection.close(); // 关闭数据库
        console.error(`MongoDB connection file: ${err}`);
    });

    db.on('disconnected', () => {
        console.log('MongoDB connection disconnected');
    });
    return db;
}

module.exports = { openDB };